package com.chuanjiabao.wisdom.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;

import com.chuanjiabao.wisdom.MainActivity;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.RefreshMessageEvent;
import com.chuanjiabao.wisdom.bean.UpdateHeadCallBackBean;
import com.chuanjiabao.wisdom.bean.UpdateStatus;
import com.chuanjiabao.wisdom.bean.UserInfoCallBackBean;
import com.chuanjiabao.wisdom.databinding.ActivityUserinfoBinding;
import com.chuanjiabao.wisdom.greendao.gen.UpdateStatusDao;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.ui.ActivityStack;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.ui.view.DialogGLC;
import com.chuanjiabao.wisdom.util.GlideUtil;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.TimeHelper;
import com.chuanjiabao.wisdom.util.TimeUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.ArriveDialog;
import com.chuanjiabao.wisdom.util.dialog.SelectSexDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import cn.carbs.android.gregorianlunarcalendar.library.data.ChineseCalendar;
import okhttp3.Call;
import okhttp3.Response;

public class UserInfoActivity extends BaseActivity {

    private ActivityUserinfoBinding binding;
    private UpdateStatusDao updateStatusDao = FApplication.getInstance().getDaoSession().getUpdateStatusDao();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_userinfo);
        binding.setActivity(this);
        initView();
        initData();
    }

    private void initData() {
        getUserInfo();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        binding.rvModuleLeft.setOnClickListener(this);
        binding.ivModuleHead.setOnClickListener(this);
        binding.tvModuleSelectDay.setOnClickListener(this);
        binding.tvModuleSelect.setOnClickListener(this);
        binding.tvModuleOk.setOnClickListener(this);
        binding.tvModuleSelectSex.setOnClickListener(this);
        binding.tvModuleRight.setOnClickListener(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvModuleRight:
                ArriveDialog arriveDialog = new ArriveDialog(this);
                arriveDialog.show();
                arriveDialog.setOnBHClickListener(position -> {
                    RefreshMessageEvent event = new RefreshMessageEvent();
                    event.setType("main");
                    event.setId(position + "");
                    EventBus.getDefault().post(event);
                    ActivityStack.getScreenManager().popAllActivityExceptOne(MainActivity.class);
                });
                break;
            case R.id.tvModuleSelectSex:
                SelectSexDialog dialog = new SelectSexDialog(this);
                dialog.show();
                dialog.setOnBHClickListener(new OnBHClickListener() {
                    @Override
                    public void onConfirmClick() {
                        sex = "2";
                        LogUtil.e("选择女性");
                        binding.tvModuleSelectSex.setText("女");
                    }

                    @Override
                    public void onCloseClick() {
                        sex = "1";
                        LogUtil.e("选择男性");
                        binding.tvModuleSelectSex.setText("男");
                    }
                });
                break;
            case R.id.tvModuleOk:
                truename = binding.etModuleTrueName.getText().toString().trim();
                if (TextUtils.isEmpty(truename)) {
                    ToastUtil.showToast("请输入名字");
                    return;
                }

                UpdateStatus bean = new UpdateStatus();
                bean.setStatus("1");
                bean.setFirst("");
                bean.setSecond("");
                bean.setThird("");
                bean.setForth("");
                updateStatusDao.insert(bean);

                updateUserInfo();
                break;
            case R.id.tvModuleSelectDay:
                Calendar calendar = Calendar.getInstance();
                if (!TextUtils.isEmpty(birthday)
                        && Long.parseLong(birthday) > 0
                ) {
                    String dateStr = TimeHelper.getInstance()
                            .getFormatedDateTime(
                                    "yyyy-MM-dd",
                                    Long.parseLong(birthday)
                            );

                    try {
                        @SuppressLint("SimpleDateFormat")
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = sdf.parse(dateStr);
                        calendar.setTime(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                DialogGLC mDialog = new DialogGLC(
                        UserInfoActivity.this,
                        !TextUtils.equals("2", birthday_type));
                mDialog.show();
                if (TextUtils.equals("2", birthday_type)) {
                    mDialog.initCalendar(
                            new ChineseCalendar(true,
                                    calendar.get(Calendar.YEAR),
                                    calendar.get(Calendar.MONTH) + 1,
                                    calendar.get(Calendar.DAY_OF_MONTH)));
                } else {
                    mDialog.initCalendar(calendar);
                }
                mDialog.setOnDataSelectListener((yangData, yinData, index) -> {
                    switch (index) {
                        case 0:
                            birthday_type = "1";
                            birthday = TimeUtil.timeToStr(yangData);
                            binding.tvModuleSelectDay.setText(yangData + "(阳历)");
                            break;
                        case 1:
                            birthday_type = "2";
                            birthday = TimeUtil.timeToStr(yinData);
                            binding.tvModuleSelectDay.setText(yinData + "(阴历)");
                            break;
                    }
                });
                break;
            case R.id.rvModuleLeft:
                finish();
                break;
            case R.id.ivModuleHead:
                PictureSelector.create(UserInfoActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .theme(R.style.picture_default_style)
                        .maxSelectNum(1)
                        .minSelectNum(1)
                        .imageSpanCount(4)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .previewImage(true)
                        .isCamera(true)
                        .imageFormat(PictureMimeType.PNG)
                        .isZoomAnim(true)
                        .compress(true)
                        .glideOverride(160, 160)
                        .enableCrop(true)
                        .withAspectRatio(1, 1)
                        .hideBottomControls(true)
                        .compressSavePath(getCacheDir().getAbsolutePath())
                        .freeStyleCropEnabled(false)
                        .showCropFrame(true)
                        .showCropGrid(true)
                        .isGif(false)
                        .openClickSound(false)
                        .previewEggs(true)
                        .minimumCompressSize(100)
                        .isDragFrame(false)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.tvModuleSelect:
                startActivity(
                        new Intent(
                                UserInfoActivity.this,
                                UserInfoPhoneActivity.class
                        )
                );
                break;
        }
    }

    public void getUserInfo() {
        HTTPAPI.getInstance().getUserInfo(new StringCallback() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(UserInfoActivity.this, s);
                } else {
                    UserInfoCallBackBean bean = GsonUtil.GsonToBean(s, UserInfoCallBackBean.class);
                    binding.setBean(bean.getData());
                    if (TextUtils.isEmpty(bean.getData().getAvatar())) {
                        avatar = "";
                        binding.ivModuleHead.setImageResource(R.mipmap.icon_default_user);
                    } else {
                        avatar = bean.getData().getAvatar();
                        GlideUtil.setCircleMethod(
                                UserInfoActivity.this,
                                bean.getData().getAvatar(),
                                binding.ivModuleHead
                        );
                    }
                    truename = bean.getData().getTruename();
                    city = bean.getData().getCity() + "";
                    province = bean.getData().getProvince() + "";
                    address = bean.getData().getAddress();
                    district = bean.getData().getDistrict() + "";
                    switch (bean.getData().getSex()) {
                        case 0:
                            sex = "";
                            break;
                        case 1:
                            sex = "1";
                            break;
                        case 2:
                            sex = "2";
                            break;
                        default:
                    }
                    birthday = bean.getData().getBirthday() + "";
                    if (2 != bean.getData().getBirthday_type()) {
                        birthday_type = "1";
                        binding.tvModuleSelectDay.setText("阳历." + TimeUtil.ChatToTimeStr(bean.getData().getBirthday()));
                    } else {
                        birthday_type = "2";
                        binding.tvModuleSelectDay.setText("阴历." + TimeUtil.ChatToTimeStr(bean.getData().getBirthday()));
                    }

                    int length = binding.etModuleTrueName.getText().length();
                    binding.etModuleTrueName.setSelection(length);
                }
            }
        });
    }

    String sex = "1", birthday = "", birthday_type = "", truename = "", province = "", city = "",
            district = "", address = "", avatar = "";

    public void updateUserInfo() {
        HTTPAPI.getInstance().udpateUserInfo(sex, birthday, birthday_type,
                truename, province, city, district, address, avatar,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LogUtil.e("个人信息修改完毕-->" + s);
                        if (!StringUtil.isFail(s)) {
                            StringUtil.showFail(UserInfoActivity.this, s);
                        } else {
                            RefreshMessageEvent event = new RefreshMessageEvent();
                            event.setType("refresh");
                            EventBus.getDefault().post(event);

                            SpUtils.put("module_truename", truename);
                            SpUtils.put("module_userinfo_head", avatar);
                            finish();
                        }
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK
                && requestCode == PictureConfig.CHOOSE_REQUEST
        ) {
            ArrayList<LocalMedia> selectList = (ArrayList<LocalMedia>) PictureSelector.obtainMultipleResult(data);
            String capath = selectList.get(0).getCompressPath();
            GlideUtil.setCircleMethod(UserInfoActivity.this, capath, binding.ivModuleHead);
            updateHead(new File(capath));
        }
    }

    public void updateHead(File file) {
        HTTPAPI.getInstance().updateHead(file, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(UserInfoActivity.this, s);
                } else {
                    UpdateHeadCallBackBean bean = GsonUtil.GsonToBean(s, UpdateHeadCallBackBean.class);
                    avatar = bean.getData();
                }
            }
        });
    }

}

